// subpkg_order/pages/order.js
const db = wx.cloud.database()
const todos = db.collection('orders_data')
const app = getApp()

const state = ['un_finish', 'in_finish', 'finish', 'cancel']

Page({
  // 切换状态
  switchTab(e){
    if(!app.globalData.isUserInfo){
      wx.showToast({
        title: '您还未登录哦',
        icon: 'error'
      })
      return
    }
    const idx = e.currentTarget.dataset.idx
    this.setData({ 
      actIndex: idx,
      skipNum: 0,
      orderData: []
     })
    if(idx === 0) this.getOrderData(state[idx])
    if(idx === 1) this.getOrderData(state[idx])
    if(idx === 2) this.getOrderData(state[idx])
    if(idx === 3) this.getOrderData(state[idx])
  },
  // 展开信息订单信息
  showOrderInfo(e){
    const idx = e.currentTarget.dataset.index
    let newStatusList = [...this.data.itemShowState]
    newStatusList[idx] = !newStatusList[idx]
    this.setData({
      itemShowState: newStatusList
    })
  },
  // 确认订单
  switchState(e){
    wx.showModal({
      title: '提示',
      content: '是否确定完成拍摄内容？',
      complete: (res) => {
        if (res.confirm) {
          const id = e.currentTarget.dataset.id
          console.log(id);
          wx.cloud.callFunction({
            name: 'set_order_state',
            data: {
              id,
              state: 'finish'
            }
          }).then(res => {
            let data = this.data.orderData
            data = data.filter(obj => obj._id != id)
            this.setData({ orderData: data })
          })
        }
      }
    })
    
  },
  // 获取订单数据
  async getOrderData(val){
    await wx.showLoading({
      title: '获取中',
    })
    // 获取数据总条数
    const totalNum = await todos.where({ orderState: val }).count()
    console.log(this.data.skipNum,totalNum.total);

    if(this.data.skipNum >= totalNum.total){
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      })
      return
    }

    const res = await wx.cloud.callFunction({
      name: 'get_user_order',
      data: {
        state: val,
        skipNum: this.data.skipNum,
        perNum: this.data.perNum,
        isUser: true
      }
    })
  
    const newData = this.data.orderData
    newData.push(...res.result.data)
    console.log(newData);
    
    this.setData({ 
      orderData: newData,
      itemShowState: newData.map(() => false),
      skipNum: this.data.skipNum + this.data.perNum
     })
    await wx.hideLoading()
  },
  /**
   * 页面的初始数据
   */
  data: {
    actIndex: 0,
    orderData: [], // 订单数据
    itemShowState: [], // 控制每个订单信息的显示隐藏
    perNum: 10, //
    skipNum: 0, //
    showLogin: false,
  },
  async getUserInfo(){
    // 获取openid
    const res = await wx.cloud.callFunction({
      name: 'get_openId'
    })
    // 获取对应用户数据
    const db = wx.cloud.database()
    const userData = await db.collection('userInfo').where({
      openid: res.result.openid
    }).get()

    // 若数据库有该用户则将信息同步页面
    if(userData.data.length > 0){
      this.getOrderData(state[this.data.actIndex] || 'un_finish')
    }else{
      wx.requirePrivacyAuthorize({
        success: () => {
          this.setData({ showLogin: true })
        },
        fail: () => {
          wx.showToast({
            title: '您还未登录哦',
            icon: 'error'
          })
        }
      })
    }
  }, 

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ actIndex: parseInt(options.idx) || 0 })
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getOrderData(state[this.data.actIndex])
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})